<?php

class Admin_UsertypeController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
        $adminValidation = new Validations_User();
        $valid = $adminValidation->hasidentity();
        if ($valid) {
            if ($adminValidation->getUserTypeId() != 1) {
                $this->view->message = "You are not admin.";
                Zend_Auth::getInstance()->clearIdentity();
                $this->_redirect('/admin/login');
            }
        } else {
            $this->_redirect('/admin/login');
        }
        $this->_helper->layout->setLayout('admin');
    }

    public function indexAction() {
        $userType = new Users_Model_UserType();
        $this->view->userTypes = $userType->fetchAll();
    }

    public function viewAction() {
        $this->indexAction();
    }

    public function addAction() {
        $form = new Users_Form_UserTypeAdd();
        $this->view->addForm = $form;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $typeDb = new Users_Model_UserType();
                $typeDb->createUserType(array(
                    'type' => $values['usertype']
                ));
                $this->_redirect('/admin/usertype');
            }
        }
    }

    public function updateAction() {

        $form = new Users_Form_Usertypeupdate();

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $typeid = $values['sr'];
                $db = new Users_Model_UserType();
                $db->updateUserType($values, $typeid);
                $this->_redirect('/admin/usertype');
            }
        } else {
            // set filters and validators for GET input
            $filters = array(
                'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
            );
            $validators = array(
                'id' => array('Int')
            );
            $input = new Zend_Filter_Input($filters, $validators);
            $input->setData($this->getRequest()->getParams());


            //get value from database
            $db = new Users_Model_UserType();
            $result = $db->getUserType($input->id);
            $form->mainForm($result);
        }
        $this->view->updateForm = $form;
    }

}

